<?php


namespace app\index\Service;


use GuzzleHttp\Client;
use QL\QueryList;
use think\Db;

class Index
{
    public static function getResult($ksh, $xm)
    {
        $result = null;
        // 启动事务
        Db::startTrans();
        try {

            // 判断数据库里是否存在数据
            $result = Db::name('hlcb_result')
                ->where('ksh', trim($ksh))
                ->where('xm', trim($xm))
                ->where('status', 1)
                ->find();
            if ($result) {
                Db::commit();
                return $result;
            }

            // 不存在 则爬取华立数据

            $client = new Client();
            $response = $client->post("http://tw.hualixy.com:808/getform2.php", [
                'form_params' => [
                    'xh' => $ksh,
                    'name' => $xm,
                    '提交' => '提交',
                ],
            ]);

            $table = QueryList::html($response->getBody())->find('table');

            // 采集表的每行内容
            $tableRows = $table->find('tr:gt(0)')->map(function ($row) {
                return $row->find('td')->texts()->all();
            })->toArray();

            if (empty($tableRows)) {
                Db::commit();
                return $result;
            }

            $master_data = [
                'ksh' => trim($ksh),
                'xm' => trim($xm),
            ];
            // 爬虫有数据
            foreach ($tableRows as $item) {
                $data = [];
                if (!empty($item[0])) {
                    $data = [
                        'ksh' => trim($ksh),
                        'kmdm' => trim($item[0]),
                        'kmmc' => trim($item[1]),
                        'score' => trim($item[2]),
                    ];
                    Db::name('hlcb_result_detail')->insert($data);
                } else {
                    if (trim($item[1]) == '省统考总分') {
                        $master_data['skzf'] = trim($item[2]);
                    }
                    if (trim($item[1]) == '五科总分') {
                        $master_data['wkzf'] = trim($item[2]);
                        // 院校信息
                        preg_match('/\d+/', $item[3], $r);
                        preg_match('/\D+/', $item[3], $r2);
                        $master_data['yxdm'] = $r[0] ?? '';
                        $master_data['yxmc'] = $r2[0] ?? '';
                        // 专业信息
                        preg_match('/\d+/', $item[4], $r3);
                        preg_match('/\D+/', $item[4], $r4);
                        $master_data['zydm'] = $r3[0] ?? '';
                        $master_data['zymc'] = $r4[0] ?? '';
                    }
                }
            }

            Db::name('hlcb_result')->insert($master_data);
            $result = $master_data;

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return false;
        }
        return $result;
    }
}